﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Web.Script.Serialization;
using System.Text;

public partial class Search : System.Web.UI.Page
{
    security hdds;
    
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            hdds = new security();
            if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
            if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

            if (Request.QueryString["mn"] != null)
                hdds.logMenuClick(Request.QueryString["mn"].ToString());
            
            Panel pnl = (Panel)this.Master.FindControl("panel1");
            if (pnl != null)
            {
                pnl.Visible = false;
            }

            Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, true);

            if (Request.QueryString["mn"] != null)
                if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
                {
                    lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    lblHeader.Visible = false;
                    TABLE1.Visible = false;
                    TABLE2.Visible = false;
                    return;
                }

            if (!IsPostBack)
                loadObjectList();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Query Builder: Error : Page_Load : " + ex.Message);
        }
    }

    #region Page Icon and Tooltip
    private void getpageicons()
    {
        PageIcons icons = new PageIcons();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
            lblHeader.Text = "&nbsp;" + icons.geticontextfrompageset(strPagesetRowID, 2) + "&nbsp;" + lblHeader.Text;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            lblHeader.Text = "<img src=" + PageIcons.strdefaulticon.ToString() + "></img>&nbsp;" + lblHeader.Text;
        }
        finally
        {
            icons = null;
            Hdd = null;
        }
    }

    private void AddPageToolTip(DataRow drpage, ref Label lblHeader)
    {
        if (drpage != null)
        {
            if (!Page.IsPostBack)
                lblHeader.Text = lblHeader.Text + getTootipIcon(drpage);
            Literal lit = new Literal();
            lit.Text = getTooltipContent(drpage);
            td_Page_ToopTip.Controls.Add(lit);
        }
    }

    private string getTootipIcon(DataRow droPage)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return "";
            if (droPage["page_desc"].ToString().Trim() == "") return "";
            return "&nbsp;<img id=\"page_tooltip_img\" style=\"cursor:pointer;\" src=\"Images/collapse3.gif\" onClick=\"javascript:showHideTooltipDIV();\" border=\"0\"></img>";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string getTooltipContent(DataRow droPage)
    {
        if (!droPage.Table.Columns.Contains("page_desc")) return "";
        if (droPage["page_desc"].ToString().Trim() == "") return "";
        return getContent(HttpContext.Current.Server.MapPath("") + @"\scripts\pagetooltipcontent.txt").Replace("<<content>>", CommonFunctions.SafeEncode(droPage["page_desc"].ToString()));
    }

    private string getContent(string fileName)
    {
        try
        {
            if (!File.Exists(fileName))
                return "";
            string temp = "";
            StreamReader sr = new StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close();
            sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    #endregion

    #region Load Objects
    private void loadObjectList()
    {
        HDDatabase hd = new HDDatabase();
        DataSet dsSrhObj = new DataSet();
        string strJson = "";
        try
        {
            bool IncldOwner = Convert.ToBoolean(hd.GetColumnValue("select mem_value1 from sy_acr_mem where acr_id ='d6a3bb5766cd8992' and af_row_id = 'fe74bd99052fb8f6';"));
            string Sql = "select obj.af_row_id, obj.object_id, obj.object_name from sy_obj obj inner join sy_obj_acc acc on obj.object_id = acc.object_id and acc.[read] = 1 and acc.role_id='" + (Session["roleid"] != null ? Session["roleid"].ToString() : "") + "' ";
            Sql += (IncldOwner && Session["user_afrowid"] != null ? " and obj.owner_id = '" + Session["user_afrowid"].ToString() + "';" : ";");
            dsSrhObj = hd.GetDataset(Sql + "select mem_value2 as af_row_id, mem_id as object_id, mem_name as object_name, mem_value3 as IsChecked from sy_acr_mem where acr_id = '9615bf7c953cacBR' and mem_value1 = 'true';");

            cbl_search_in_obj.Items.Clear();

            foreach (DataRow dr in dsSrhObj.Tables[1].Rows)
            {
                if (dsSrhObj.Tables[0].Select("af_row_id = '" + dr["af_row_id"].ToString() + "'").Length == 0)
                {
                    DataRow drNew = dsSrhObj.Tables[0].NewRow();
                    drNew["af_row_id"] = dr["af_row_id"].ToString();
                    drNew["object_id"] = dr["object_id"].ToString();
                    drNew["object_name"] = dr["object_name"].ToString();
                    dsSrhObj.Tables[0].Rows.Add(drNew);
                }
            }
            foreach (DataRow dr in dsSrhObj.Tables[0].Select("", "object_name asc"))
            {
                ListItem liObject = new ListItem(dr["object_name"].ToString(), dr["af_row_id"].ToString());
                liObject.Attributes.Add("id", liObject.Value);
                strJson += "{\"ObjId\":\"" + liObject.Value + "\",\"IconPath\":\"" + getPageIconPath(liObject.Value) + "\"},";
                cbl_search_in_obj.Items.Add(liObject);
            }
            hfObjectDetails.Value = "[" + strJson.TrimEnd(',') + "]";
            foreach (DataRow dr in dsSrhObj.Tables[1].Select("IsChecked = 'true'"))
            {
                cbl_search_in_obj.Items.FindByValue(dr["af_row_id"].ToString()).Selected = true;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadObjectList : Error : " + ex.Message);
        }
        finally
        {
            dsSrhObj.Dispose();
        }
    }

    private string getPageIconPath(string sObjectID)
    {
        string sRet = PageIcons.strdefaulticon;
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sPageIcon = HDD.GetColumnValue("select page_icon from sy_pg where object_id in (select object_id from sy_obj where af_row_id = '" + sObjectID + "');");
            sRet = "Images/MBIcons/Medium/" + (sPageIcon != "" ? sPageIcon : "Default.PNG");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getPageIconPath : Error : " + ex.Message);
            return sRet;
        }
        return sRet;
    }

    private string applysecurity(string sql)
    {
        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                    sAFAdmin += " and " + sCustodianFilter;
                else
                    sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql + " where " + sAFAdmin;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Query Builder: applysecurity : Error : " + ex.Message);
            return sql;
        }
        return sql;
    }
    #endregion
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }
}